
const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt-nodejs');
const UserModel = require('../db/UserModel');//用户模型
const DepartmentModel = require('../db/DepartmentModel');//科室模型
const RoleModel = require('../db/RoleModel');//角色模型
const CmmuseumModel = require('../db/CmmuseumModel');//门店 模型
const Registration = require('../db/RegistrationModel');//挂号费模型
const ArrangeMesModel = require('../db/ArrangeMesModel');//人员排班表
const PatientModel = require('../db/PatientModel');//患者模型
const Registrationinfor = require('../db/RegistrationinforMation');
const authhs256 = require("../middlewares/authhs256/authentication");
const moment = require('moment');
const OperationLog = require("../db/OperationLog");
const now = () => {
    return moment().format('YYYY-MM-DD HH:mm:ss')
}
const Fun = require("../middlewares/Fun")
const SchedulingModel = require('../db/SchedulingModel');

/**
 * 时间统一用时间戳
 * 人员路由模块
 * 人员CRUD
 * 登录
 * 医生排班信息列表
 * 添加排班信息  (创建医生角色时,自动生成对应排班信息)
 * 外科治疗接诊情况
 * 修改密码
 * 医生排班信息列表复制，单个医生复制排班信息，复制最近7天的排班信息
 */

router.post('/alreadyregister', function (req, res, next) {
    if (!req.body.phone && !req.body.managerphone) {
        return res.json({ code: 201, mes: '缺少必填信息！' });
    }
    UserModel.findOne({ phone: req.body.phone || req.body.managerphone }).then((data) => {
        if (data) {
            return res.json({ code: 201, mes: '该电话号码已经存在！' });
        } else {
            return res.json({ code: 200, mes: '该电话号码可用！' });
        }
    }).catch(() => {
        return res.json({ code: 201, mes: '发生意外错误！' })
    });

});

//添加人员
router.post('/save', function (req, res) {
    const phone = req.body.phone;
    let user = req.user;
    let pare;
    //参数校验
    if (req.body.name == '' || req.body.sex == '' || req.body.phone == '' || req.body.post == '' || req.body.department == '' || req.body.shop == '' || req.body.role == '' || req.body.jurisdiction == '') {
        return res.json({
            code: 202,
            mes: '参数错误。'
        });
    }
    const doctor = new UserModel(req.body);
    doctor.password = bcrypt.hashSync(req.body.password); // 密码加密 
    UserModel.findOne({ phone: phone }).then(docs => {
        if (!docs) {// !null
            return doctor.save().then(docs => {
                pare = {
                    id: user._id,
                    name: user.name,
                    roles: user.role,
                    ip: req.ip.replace(/::ffff:/, ''),
                    time: now(),
                    Operationcontent: "添加员工成功"
                };
                OperationLog.create(pare).then(data => { }).catch(e => { })
                return RoleModel.findById(req.body.role).then(role => {
                    if (role.name == "医生" || role.name == "药房") {
                        return ArrangeMesModel.create({
                            "id": docs._id,
                            "name": req.body.name,
                            "role": role.name,
                            "arrangemes": [],
                            department: req.body.department
                        }).then(datass => {
                            return res.json({
                                code: 200,
                                mes: '添加成功.',
                                data: docs
                            });
                        })
                    } else {
                        return res.json({
                            code: 200,
                            mes: '添加成功.',
                            data: docs
                        });
                    }
                })
            }).catch(err => {
                pare.time = now();
                pare.Operationcontent = "添加员工失败"
                OperationLog.create(pare).then(data => { }).catch(e => { })
                return res.json({
                    code: 500,
                    mes: "数据库繁忙,请稍后重试.",
                    error: err
                });
            })
        } else {
            return res.json({
                code: 201,
                mes: '此人员已存在,请勿重复添加'
            });
        }
    }).catch(err => {
        return res.json({
            code: 500,
            mes: "数据库繁忙,请稍后重试.",
            error: err
        });
    })

});

//删除人员信息
router.post('/delete', function (req, res) {
    const id = req.body.id;
    UserModel.remove({ _id: id }).then(docs => {
        if (docs) {
            return res.json({
                code: 200,
                mes: '删除成功.'
            });
        }
        else {
            return res.json({
                code: 201,
                mes: '删除失败.'
            });
        }
    }).catch(err => {
        return res.json({
            code: 201,
            mes: "数据库繁忙,请稍后重试.",
            error: err
        });
    })
});

//修改人员信息
router.post('/update', function (req, res) {
    let val = req.body;
    let id = req.body.id;
    let department = req.body.department;
    if (!val.state) {
        if (!val.jurisdiction) {
            val.jurisdiction = []
        }
    }
    UserModel.findOne({ _id: id }).then(docs => {
        if (docs == null) {
            return res.json({
                code: 201,
                mes: '不存在此人员信息.'
            });
        }
        else {
            return RoleModel.findById(val.role).then(role => {
                if (role.name == "医生") {
                    return ArrangeMesModel.update({ department: docs.department[0], name: val.name }, { $set: { department: department } }).then(data => {
                        return UserModel.update({ _id: id }, { $set: val }).then(user => {
                            Fun.saveLogs(req.user, req.ip.replace(/::ffff:/, ''), "修改人员信息成功.");
                            return res.json({
                                code: 200,
                                mes: '修改成功.'
                            });
                        })
                    })
                } else {
                    return UserModel.update({ _id: id }, { $set: val }).then(user => {
                        Fun.saveLogs(req.user, req.ip.replace(/::ffff:/, ''), "修改人员信息成功.");
                        return res.json({
                            code: 200,
                            mes: '修改成功.'
                        });
                    })
                }
            });
        }
    }).catch(err => {
        Fun.saveLogs(req.user, req.ip.replace(/::ffff:/, ''), "修改人员信息修改失败.");
        return res.json({
            code: 201,
            mes: '修改失败.',
            err
        });
    })
});

//查询所有人员信息
router.get('/list', function (req, res) {
    let departments = [];
    let users = [];
    UserModel.find().then((data) => {
        users = data;
        let p1 = DepartmentModel.find({}, ['name']);
        let p2 = RoleModel.find({}, ['name']);
        let p3 = CmmuseumModel.find({}, ['name']);
        return Promise.all([p1, p2, p3]);
        // 科室多个 ，门店多个 ，角色一个     
    }).then((data) => {   // data[o] department data[1] role data[2] Cmmuseum
        const cacheObj = {};
        try {
            for (let i = 0; i < data[0].length; i++) {
                cacheObj[data[0][i]._id] = data[0][i];
            }
            for (let i = 0; i < data[1].length; i++) {
                cacheObj[data[1][i]._id] = data[1][i];
            }
            for (let i = 0; i < data[2].length; i++) {
                cacheObj[data[2][i]._id] = data[2][i];
            }
            for (let i = 0; i < users.length; i++) {
                for (let j = 0; j < users[i].department.length; j++) {
                    users[i].department[j] = cacheObj[users[i].department[j]]
                }
                users[i].role = users[i].role != "" ? cacheObj[users[i].role].name : null;
                for (let j = 0; j < users[i].shop.length; j++) {
                    users[i].shop[j] = cacheObj[users[i].shop[j]]
                }
            }
        } catch (error) {
            console.log(error)
        }
        return res.json({ code: 200, users });
    }).catch((err) => {
        return res.json({ code: 201, mes: "数据库繁忙,请稍后重试.", data: err });
    })
});
// 查找指定医生
router.get('/one/:id', function (req, res, next) {
    const id = req.params.id;
    UserModel.findById(id).then((user) => {
        return res.json({ code: 200, user });
    }).catch(() => {
        return res.json({ code: 201, mes: '发生意外错误！' });
    });
});

//登录
router.post('/login', function (req, res) {
    if (!req.body.phone || !req.body.password) {
        return res.json({ code: 201, mes: '缺少必填信息' });
    }

    let phone = req.body.phone;
    let password = req.body.password;
    let pare;
    UserModel.findOne({ phone }).then(function (user) {
        // return RoleModel.findById({_id:user.role}).then(data=>{

        // })
        pare = {
            id: user._id,
            name: user.name,
            roles: user.role,
            ip: req.ip.replace(/::ffff:/, ''),
            time: now(),
            Operationcontent: "登录成功."
        };
        if (user == null) {
            return res.json({ code: 202, mes: '登陆失败' });
        }
        if (!bcrypt.compareSync(password, user.password)) {
            pare.Operationcontent = "登陆失败.";
            OperationLog.create(pare).then(data => { }).catch(e => { })
            return res.json({ code: 203, mes: '登陆失败' });
        }
        //return res.json({ code: 200, user: user, token: authhs256.createJWT(user) });

        return res.json({
            cod: 200,
            mes: '登录成功.',
            token: authhs256.createJWT(user),
            Userinfo: {
                name: user.name,
                id: user._id,
                shop: user.shop,
                jurisdiction: user.jurisdiction,
                role: user.role
            }
        });
    }).catch(function (err) {
        pare.Operationcontent = "登陆失败.";
        pare.time = now();
        OperationLog.create(pare).then(data => { }).catch(e => { })
        return res.json({ code: 204, mes: '登陆失败' });
    });
});

//添加排班信息  (创建医生角色时,自动生成对应排班信息)
router.post('/addarrangemes', function (req, res) {
    let temp = new ArrangeMesModel(req.body);
    temp.save().then(arrangemes => {
        return res.json({
            code: 200,
            mes: '添加成功.'
        });
    }).catch(err => {
        return res.json({
            code: 201,
            mes: '添加失败'
        });
    })
});

//医生排班信息列表
router.post('/listscheduling', function (req, res) {
    const starttime = new Date(req.body.starttime).getTime();//排班列表开始日期
    const endtime = new Date(req.body.endtime).getTime();//排班列表结束日期
    let pageindex = req.body.pageindex;//页码
    let pagesize = req.body.pagesize;//每页显示数据条数
    ArrangeMesModel.find({}).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).then(users => {//根据开始和结束时间获取排班列表
        if (users == null || users.length == 0) {
            ArrangeMesModel.find({ state: "启用", }).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).then(users => {
                for (let a = 0; a < users.length; a++) {
                    if (users[a].arrangemes instanceof Array) {
                        let newArr = [];
                        for (let b = 0; b < users[a].arrangemes.length; b++) {
                            if (starttime <= (new Date(users[a].arrangemes[b].arrangetime).getTime()) && (new Date(users[a].arrangemes[b].arrangetime).getTime()) <= endtime) {
                                newArr.push(users[a].arrangemes[b])
                            }
                        }
                        users[a].arrangemes = newArr
                    }
                }
                return res.json({
                    code: 200,
                    mes: '查询成功。',
                    data: users
                });
            }).catch(err => {
                return res.json({
                    code: 201,
                    mes: '查询失败'
                });
            })
        }
        else {
            for (let a = 0; a < users.length; a++) {
                if (users[a].arrangemes instanceof Array) {
                    let newArr = [];
                    for (let b = 0; b < users[a].arrangemes.length; b++) {
                        if (starttime <= (new Date(users[a].arrangemes[b].arrangetime).getTime()) && (new Date(users[a].arrangemes[b].arrangetime).getTime()) <= endtime) {
                            newArr.push(users[a].arrangemes[b])
                        }
                    }
                    users[a].arrangemes = newArr
                }
            }
            return res.json({
                code: 200,
                mes: '查询成功。',
                data: users
            });
        }

    }).catch(err => {
        return res.json({
            code: 201,
            mes: '查询失败'
        });
    })
});

//修改排班医生科室
router.post('/updatedepartment', function (req, res) {
    let { id, department, doctorname, role } = req.body;
    if (!id || !department || !doctorname) {
        return res.json({
            code: 202,
            mes: '参数有误。'
        });
    }
    ArrangeMesModel.findOne({ id }).then(doc => {
        if (doc) {
            return ArrangeMesModel.update({ id: id }, { $set: { department: department } }).then(result => {
                return result
            })
        } else {
            return ArrangeMesModel.create({
                "id": id,
                "name": doctorname,
                "role": role || "医生",
                "arrangemes": [],
                department: department
            }).then(datass => {
                return true
            })
        }
    }).then(data => {
        return res.json({
            code: 200,
            mes: "修改成功.",
            data
        })
    }).catch(err => {
        return res.json({
            code: 201,
            mes: "发生意外错误.",
            err
        })
    })
});

//修改医生班次
router.post('/updateclasses', function (req, res) {
    const time = req.body.time;//排班时间
    const name = req.body.name;//排班名称
    const id = req.body.id;//医生ID
    const doctorname = req.body.doctorname;
    const role = req.body.role;
    let user = req.user
    if (!time || !name || !id) {
        return res.json({
            code: 202,
            mes: '参数有误。'
        });
    }
    ArrangeMesModel.findOne({ 'id': id, 'arrangemes.arrangetime': time }).then(docs => {//判断此医生id和此时间是否存在排班信息,存在则修改,否则就添加此排班信息
        if (docs) {//存在此排班信息
            ArrangeMesModel.update({ 'id': id, 'arrangemes.arrangetime': time }, {
                $set: {
                    "arrangemes.$": {
                        "arrangetime": time,
                        "arrangename": name
                    }
                }
            }).then(result => {
                Fun.saveLogs(user, req.ip.replace(/::ffff:/, ''), "修改排班时间信息成功");
                return res.json({
                    code: 200,
                    mes: '修改排班时间信息成功.'
                });
            }).catch(err => {
                Fun.saveLogs(user, req.ip.replace(/::ffff:/, ''), "修改排班时间信息失败");
                return res.json({
                    code: 201,
                    mes: '修改排班时间信息失败',
                    data: err
                });
            })
        } else {//不存在
            ArrangeMesModel.update({ id: id }, {//往对应医生的排班信息数组中添加前端传的时间和名称
                $push: {
                    arrangemes: {
                        arrangetime: time,
                        arrangename: name
                    }
                }
            }).then(result => {
                let temp = new ArrangeMesModel({
                    "id": id,
                    "name": doctorname,
                    "role": role,
                    "arrangemes": [
                        {
                            "arrangetime": time,
                            "arrangename": name
                        }],
                });
                if (result.n == 0) {
                    return temp.save().then(arrangemes => {
                        return true
                    })
                } else {
                    return false
                }
            }).then(info => {
                Fun.saveLogs(user, req.ip.replace(/::ffff:/, ''), "添加排班时间信息成功");
                return res.json({
                    code: 200,
                    mes: '添加成功.'
                });
            }).catch(() => {
                Fun.saveLogs(user, req.ip.replace(/::ffff:/, ''), "添加排班时间信息失败");
                return res.json({
                    code: 201,
                    mes: '修改排班时间信息失败'
                });
            })
        }
    }).catch(err => {
        return res.json({
            code: 202,
            mes: '查询错误.'
        });
    })

});

//外科治疗接诊情况
router.get('/listsurgical', function (req, res) {
    const temp = req.query.state;//0 : 为今日接诊  1:历史记录
    const date = Date.now();
    if (temp == 0 || temp == undefined || temp == "") {
        PatientModel.find({ 'registrationmes.receptiontime': { $gte: temp, $lte: temp } }).then(patient => {
            return res.json({
                code: 200,
                mes: '今日接诊情况查询',
                data: patient
            });
        }).catch(err => {
            return res.json({
                code: 201,
                mes: '查询失败.'
            });
        })
    } else if (temp == 1) {
        PatientModel.find({ 'registrationmes.receptiontime': { $lt: date } }).then(patient => {
            return res.json({
                code: 200,
                mes: '今日接诊情况查询',
                data: patient
            });
        }).catch(err => {
            return res.json({
                code: 201,
                mes: '查询失败.'
            });
        })
    }
});

//修改密码
router.post('/changePassWord', authhs256.ensureAuthenticated, (req, res) => {
    const { userPassword, newUserPassword } = req.body;
    const { _id, name } = req.user;
    let user = req.user
    if (!userPassword || !newUserPassword) {
        return res.json({
            code: 201,
            msg: "缺少必要参数!"
        })
    }
    return UserModel.findOne({ _id: _id }).then(data => {
        if (!data || !bcrypt.compareSync(userPassword, data.password)) {
            Fun.saveLogs(user, req.ip.replace(/::ffff:/, ''), "修改密码失败");
            return res.json({
                code: 201,
                msg: "修改密码错误!"
            })
        } else {
            data.password = bcrypt.hashSync(newUserPassword);
            return data.save().then(data => {
                Fun.saveLogs(user, req.ip.replace(/::ffff:/, ''), "修改密码成功");
                return res.json({
                    code: 200,
                    msg: "修改密码成功!"
                })
            })
        }
    }).catch(err => {
        return res.json({
            code: 500,
            msg: "发生错误!"
        })
    })
});

//给医生排班信息数组重新排序  -升序
function compare(property) {
    return function (a, b) {
        var value1 = Date.parse(a[property]);
        var value2 = Date.parse(b[property]);
        return value1 - value2;
    }
}
//医生排班信息列表复制，单个医生复制排班信息，复制最近7天的排班信息
router.get("/copyscheduling", (req, res) => {
    if (!req.query.id || !req.query.time) {
        return res.json({
            code: 201,
            mes: '参数错误。'
        });
    }
    let id = req.query.id;//唯一ID
    let time = req.query.time;//本周周一的日期
    let month = time.split('/');//分割日期
    let day;
    let user = req.user;
    if (month[2].length == 2) {
        day = time.substring(time.length - 2);
    } else {
        day = time.substring(time.length - 1);
    };
    let weektime = [];//旧排班信息
    let newArr = [];//新排班信息
    ArrangeMesModel.findOne({ id: id }).then(docs => {
        let thisday = new Date(month[0], month[1] - 1, month[2]).getTime();
        if (docs) {
            weektime = docs.arrangemes.sort(compare('arrangetime'));
            for (let i = 0; i < weektime.length; i++) {
                let weektimes = weektime[i].arrangetime.split('/')
                var d = new Date(weektimes[0], weektimes[1] - 1, weektimes[2]);
                if (thisday >= d.getTime()) {
                    newArr.push({
                        "arrangetime": moment(d.getTime()).add(7, 'days').format('YYYY/M/D'),
                        "arrangename": weektime[i].arrangename
                    });
                }
            }
            return newArr;
        }
        else {
            return res.json({
                code: 201,
                mes: '此ID不存在!'
            });
        }
    }).then(arr => {
        ArrangeMesModel.update({ id: id }, {//往对应医生的排班信息数组中添加时间和名称
            $addToSet: {
                arrangemes: { $each: newArr }
            }
        }).then((data) => {
            Fun.saveLogs(user, req.ip.replace(/::ffff:/, ''), "复制排班成功");
            return res.json({
                code: 200,
                mes: '复制成功。'
            });
        }).catch(err => {
            Fun.saveLogs(user, req.ip.replace(/::ffff:/, ''), "复制排班失败");
            return res.json({
                code: 201,
                mes: '发生意外错误!',
                data: err
            });
        })
    }).catch(err => {
        return res.json({
            code: 201,
            mes: '发生意外错误!',
            data: err
        });
    })
});
//完成登记并分诊--医生排班信息列表
router.post('/savePatient', function (req, res) {
    const starttime = new Date(req.body.starttime).getTime();//排班列表开始日期
    const endtime = new Date(req.body.endtime).getTime();//排班列表结束日期
    let pageindex = req.body.pageindex || 1;//页码
    let pagesize = req.body.pagesize || 20;//每页显示数据条数
    let nowtime = moment().format('YYYY/M/D');
    let time = req.body.time;//时间点，时间段的后半段
    let department = req.body.department;//科室id
    let doctorname = req.body.doctorname;//医生ID
    let arr = [];
    let objarr = [];//保存根据传入的时间段判断的有排班的医生
    if (time && department && doctorname) {
        SchedulingModel.find({ 'workingtime.starttime': { $lte: time }, 'workingtime.endtime': { $gte: time }, state: '启用' }).then(scheduling => {//时间段转化成对应班次名称
            return UserModel.find({ _id: doctorname }, ['name']).then(doctor => {//根据医生ID获取医生名称
                return ArrangeMesModel.find({ 'arrangemes.arrangetime': nowtime, department: department, name: doctor[0].name }).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).lean(true).then(users => {//根据时间，科室，医生名称查询排班信息
                    for (let i = 0; i < users.length; i++) {
                        arr = users[i].arrangemes;
                        for (let j = 0; j < arr.length; j++) {
                            if (arr[j].arrangetime == nowtime) {
                                for (let s = 0; s < scheduling.length; s++) {
                                    if (arr[j].arrangename != scheduling[s].name) {

                                    } else {
                                        objarr.push(users[i]);
                                    }
                                }
                            }
                        }
                    }
                    return Promise.all(objarr.map(velues => {
                        return UserModel.findOne({ _id: velues.id }).then(data => {
                            if (data) {
                                velues.alreadyaccepts = data.alreadyaccepts || 0;//待接诊人数
                                velues.totreat = data.totreat || 0;//已接诊人数
                                velues.imgURL = data.imgURL || "";//医生头像地址
                            }
                            return velues
                        })
                    }))
                })
            })

        }).then(reginforarr => {
            return Promise.all(reginforarr.map(item => {
                return Registrationinfor.find({ 'doctor.id': item.id, receptiontime: { $gte: moment().format('YYYY-MM-DD 00:00:00'), $lte: moment().format('YYYY-MM-DD 23:59:59') } }).then(reginfor => {

                    for (let i = 0; i < reginfor.length; i++) {
                        if (reginfor[i].receptionstate == 2) {
                            item.totreat++;
                        } else {
                            item.alreadyaccepts++;
                        }
                    }
                    return item;
                })
            }))
        }).then(datass => {
            return Promise.all(datass.map(value => {
                return DepartmentModel.findOne({ _id: value.department }).then(parents => {
                    value.department = { id: parents._id, name: parents.name };
                    value.arrangemes = null;
                    return value
                })
            }))
        }).then(datass => {
            return res.json({
                code: 200,
                mes: '查询成功。',
                data: datass
            });
        })
    } else if (time && !department && !doctorname) {
        SchedulingModel.find({ 'workingtime.starttime': { $lte: time }, 'workingtime.endtime': { $gte: time }, state: '启用' }).then(scheduling => {//时间段转化成对应班次名称
            return ArrangeMesModel.find({ 'arrangemes.arrangetime': nowtime }).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).lean(true).then(users => {//根据时间查询排班信息,获取当天有排班的医生
                for (let i = 0; i < users.length; i++) {
                    arr = users[i].arrangemes;//获取当前医生的所有排班信息
                    for (let j = 0; j < arr.length; j++) {
                        if (arr[j].arrangetime != nowtime) {
                        } else {//找到医生当天的排班数据
                            for (let s = 0; s < scheduling.length; s++) {
                                if (arr[j].arrangename != scheduling[s].name) {//判断医生当天排的是早班，晚班或全班
                                } else {
                                    objarr.push(users[i]);//获取当天当前时间有排班的数据
                                }
                            }
                        }
                    }
                }
                return Promise.all(objarr.map(velues => {
                    return UserModel.findOne({ _id: velues.id }).then(data => {
                        if (data) {
                            velues.alreadyaccepts = data.alreadyaccepts || 0;//已接诊人数
                            velues.totreat = data.totreat || 0;//待接诊人数
                            velues.imgURL = data.imgURL || "";//医生头像地址
                        }
                        return velues
                    })
                }))
            })
        }).then(reginforarr => {
            return Promise.all(reginforarr.map(item => {
                return Registrationinfor.find({ 'doctor.id': item.id, receptiontime: { $gte: moment().format('YYYY-MM-DD 00:00:00'), $lte: moment().format('YYYY-MM-DD 23:59:59') } }).then(reginfor => {
                    for (let i = 0; i < reginfor.length; i++) {
                        if (reginfor[i].receptionstate == 2) {
                            item.totreat++;
                        } else {
                            item.alreadyaccepts++;
                        }
                    }
                    return item;
                })
            }))
        }).then(datass => {
            return Promise.all(datass.map(value => {
                return DepartmentModel.findOne({ _id: value.department }).then(parents => {
                    value.department = { id: parents._id, name: parents.name };
                    value.arrangemes = null;
                    return value
                })
            }))
        }).then(datass => {
            return res.json({
                code: 200,
                mes: '查询成功。',
                data: datass
            });
        })
    } else if (time && department && !doctorname) {
        SchedulingModel.find({ 'workingtime.starttime': { $lte: time }, 'workingtime.endtime': { $gte: time }, state: '启用' }).then(scheduling => {//时间段转化成对应班次名称
            return ArrangeMesModel.find({ 'arrangemes.arrangetime': nowtime, department: department }).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).lean(true).then(users => {//根据时间，科室名称查询排班信息
                for (let i = 0; i < users.length; i++) {
                    arr = users[i].arrangemes;
                    for (let j = 0; j < arr.length; j++) {
                        if (arr[j].arrangetime == nowtime) {
                            for (let s = 0; s < scheduling.length; s++) {
                                if (arr[j].arrangename != scheduling[s].name) {

                                } else {
                                    objarr.push(users[i]);
                                }
                            }
                        }
                    }
                }
                return Promise.all(objarr.map(velues => {
                    return UserModel.findOne({ _id: velues.id }).then(data => {
                        if (data) {
                            velues.alreadyaccepts = data.alreadyaccepts || 0;//待接诊人数
                            velues.totreat = data.totreat || 0;//已接诊人数
                            velues.imgURL = data.imgURL || "";//医生头像地址
                        }
                        return velues
                    })
                }))
            })
        }).then(reginforarr => {
            return Promise.all(reginforarr.map(item => {
                return Registrationinfor.find({ 'doctor.id': item.id, receptiontime: { $gte: moment().format('YYYY-MM-DD 00:00:00'), $lte: moment().format('YYYY-MM-DD 23:59:59') } }).then(reginfor => {
                    for (let i = 0; i < reginfor.length; i++) {
                        if (reginfor[i].receptionstate == 2) {
                            item.totreat++;
                        } else {
                            item.alreadyaccepts++;
                        }
                    }
                    return item;
                })
            }))
        }).then(datass => {
            return Promise.all(datass.map(value => {
                return DepartmentModel.findOne({ _id: value.department }).then(parents => {
                    value.department = { id: parents._id, name: parents.name };
                    value.arrangemes = null;
                    return value
                })
            }))
        }).then(datass => {
            return res.json({
                code: 200,
                mes: '查询成功。',
                data: datass
            });
        }).catch(err => {
            return res.json({
                code: 201,
                mes: '查询失败'
            });
        })
    }

});
//医生排班信息列表复制，复制当前列表所有医生
router.post("/copyall", (req, res) => {
    if (!req.body.id || !req.body.time) {
        return res.json({
            code: 201,
            mes: '参数错误。'
        });
    }
    let query;
    try {
        query = { id: { $in: JSON.parse(req.body.id) } }
    } catch (error) {
        return res.json({
            code: 201,
            mes: '参数格式错误。'
        });
    }
    let time = req.body.time;//本周周一的日期
    let month = time.split('/');//分割日期
    let user = req.user;
    let weektime = [];//旧排班信息
    return ArrangeMesModel.find(query).then(docs => {
        let thisday = new Date(month[0], month[1] - 1, month[2]).getTime();
        for (let a = 0; a < docs.length; a++) {
            let newArr = [];//新排班信息
            weektime = docs[a].arrangemes.sort(compare('arrangetime'));
            for (let i = 0; i < weektime.length; i++) {
                let weektimes = weektime[i].arrangetime.split('/')
                var d = new Date(weektimes[0], weektimes[1] - 1, weektimes[2]);
                if (thisday >= d.getTime()) {
                    newArr.push({
                        "arrangetime": moment(d.getTime()).add(7, 'days').format('YYYY/M/D'),
                        "arrangename": weektime[i].arrangename
                    });
                }
            }
            docs[a].arrangemes = newArr
        }
        return docs;
    }).then(arr => {
        return Promise.all(arr.map(value => {
            return ArrangeMesModel.update({ id: value.id }, {//往对应医生的排班信息数组中添加时间和名称
                $addToSet: {
                    arrangemes: { $each: value.arrangemes }
                }
            }).then(data => {
                return true
            })
        }));
    }).then(data => {
        Fun.saveLogs(user, req.ip.replace(/::ffff:/, ''), "复制上周排班成功");
        return res.json({
            code: 200,
            mes: '复制成功。',
            data: data
        });
    }).catch(err => {
        Fun.saveLogs(user, req.ip.replace(/::ffff:/, ''), "复制上周排班失败");
        return res.json({
            code: 201,
            mes: '发生意外错误!',
            data: err
        });
    })
});

module.exports = router;
